<?php
/**
 * Created by PhpStorm.
 * User: suruixiang
 * Date: 2017/10/9
 * Time: 上午10:27
 */
namespace app\index\model;

use think\Model;

class MobileSend extends Model
{
    /**
     * 根据单字段获取信息
     * @param $user_name
     * @param string $fields
     * @return object
     */
    public function getInfoByField($field_name, $field_value, $fields = '*')
    {
        return $this->where($field_name, $field_value)->field($fields)->order('id desc')->find();
    }

    /**
     * 添加发送记录
     * @param $mobile
     * @param $code
     * @return int
     */
    public function addData($mobile, $code)
    {
        return $this->insertGetId([
            'mobile' => $mobile,
            'code'   => $code,
            'send_time' => time(),
            'effective_time' => time() + 5*60
        ]);
    }

    /**
     * 检测验证码
     * @param $mobile
     * @param $code
     * @return array
     */
    public function checkCode($mobile, $code)
    {
        $return = [
            'status' => 1,
        ];
        $code_data = $this->where([
            'mobile' => $mobile,
            'code'   => $code
        ])->find();
        if (!$code_data) {
            $return['status'] = 0;
            $return['msg'] = '验证码不正确';
        } elseif ($code_data['use_state'] == 1) {
            $return['status'] = 0;
            $return['msg'] = '验证码已使用';
        } elseif ($code_data['effective_time'] < time()) {
            $return['status'] = 0;
            $return['msg'] = '验证码已失效';
        }
        $this->where([
            'mobile' => $mobile,
            'code'   => $code
        ])->update([
            'use_state' => 1,
            'use_time'  => time()
        ]);
        return $return;
    }
}